<script lang="ts" setup>
import { ref, unref } from 'vue'
import { formSchema, setDeptTreeParams } from './dept.data'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { deptApi } from '@/api/sys/deptApi'
import type { DeptAddReq, DeptUpdateReq } from '@/model/sys/deptModel'

defineOptions({ name: 'DeptModal' })

const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true)
const model = ref({})

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  model,
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    setFieldsValue({ ...data.record })
    setDeptTreeParams({
      excludeDeptIds: [data.record.deptId],
    })
  }
  else {
    setDeptTreeParams({})
  }
})

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    if (unref(isUpdate))
      await deptApi.update(values as DeptUpdateReq)
    else
      await deptApi.add(values as DeptAddReq)

    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs" :min-height="300" :title="isUpdate ? '更新' : '新增'" @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
